package com.customer.ostrich.util;

import com.customer.ostrich.annotation.SelfFeignClient;
import com.customer.ostrich.controller.HelloWorld;
import com.customer.ostrich.feignApi.CustomerClient;
import feign.Feign;
import feign.Logger;
import feign.jackson.JacksonDecoder;
import feign.jackson.JacksonEncoder;
import feign.okhttp.OkHttpClient;
import org.apache.commons.lang3.StringUtils;

/**
 * @author HuTongFu
 * @since 2019/6/30 15:21
 */
public class FeignUtil<T> {

    /**
     * 解析自定义feign的注解
     *
     * @return url
     */
    private String url(Class<T> clzss) {
        SelfFeignClient annotation = clzss.getAnnotation(SelfFeignClient.class);
        if (annotation == null) {
            System.out.println("该类没有指定注解");
            return null;
        }
        return annotation.url();
    }


    public T send(Class<T> vClass) {
        String baseUrl = url(vClass);
        if (baseUrl == null || StringUtils.isBlank(baseUrl)) {
            throw new RuntimeException("调用的服务Url 为空");
        }
        return Feign.builder()
                .logger(new Logger.JavaLogger().appendToFile("logs/http.log"))
                .logLevel(Logger.Level.FULL)
                .client(new OkHttpClient())
                .encoder(new JacksonEncoder())
                .decoder(new JacksonDecoder())
                .target(vClass, baseUrl);
    }

    public static void main(String[] args) {
        CustomerClient send = new FeignUtil<CustomerClient>()
                .send(CustomerClient.class);
        HelloWorld helloWorld = new HelloWorld();
        helloWorld.setParam("test1");
        HelloWorld ostrich = send.testFeignApiHasParameterBJson(helloWorld);
    }
}
